package com.hk.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.reggie.common.CustomException;
import com.hk.reggie.common.R;
import com.hk.reggie.entity.Employee;
import com.hk.reggie.entity.Setmeal;
import com.hk.reggie.entity.SetmealDish;
import com.hk.reggie.mapper.SetmealMapper;
import com.hk.reggie.service.SetmealDishService;
import com.hk.reggie.service.SetmealService;
import com.hk.reggie.vo.SetmealVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>  implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时保存套餐和菜品的关联关系
     * @param setmealVo
     */
    @Transactional
    public void saveWithDish(SetmealVo setmealVo) {
        //保存套餐的基本信息，操作setmeal表
        this.save(setmealVo);

        //保存套餐和菜品的关联信息，操作setmeal_dish
        List<SetmealDish> setmealDishes = setmealVo.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealVo.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
    }

    @Transactional
    public void removeWithDish(List<Long> ids) {

        //查询是否是停售状态
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids).eq("status", 1);
        int count = this.count(queryWrapper);
        if(count > 0){
            //如果不能删除则抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }


        //先删除套餐表
        this.removeByIds(ids);

        //再删除关系表
        setmealDishService.remove(new QueryWrapper<SetmealDish>().in("setmeal_id", ids));

    }


}
